<template>
  <div>
    <el-card>
      <el-form :label-position="labelPosition" label-width="100px" style="max-width: 100%">
        <el-form-item label="SPU名称">
          <el-input v-model="spuParams.spuName" style="width: 200px" />
        </el-form-item>

        <el-form-item label="SPU品牌">
          <el-select v-model="spuParams.tmId" placeholder="请输入你的品牌">
            <el-option v-for="item in trademark" :key="item.id" :label="item.tmName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="SPU描述" style="width: 600px">
          <el-input v-model="spuParams.description" type="textarea" />
        </el-form-item>

        <el-form-item label="SPU图片">
          <el-upload v-model:file-list="firstImgList" action="/api/admin/product/fileUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :before-upload="handleBeforeUpload">
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="SPU销售属性">
          <el-select v-model="spuSaleAttr" :placeholder="`还剩${unselectSaleAttr}未选择`">
            <el-option v-for="item in allSaleAttr" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>

          <el-button :disabled="spuSaleAttr == ''" style="margin-left: 10px" type="primary" @click="addSaleAttr">添加属性</el-button>

          <el-table :data="saleAttrTable" style="width: 100%">
            <el-table-column type="index" label="序号" width="180" />
            <el-table-column prop="saleAttrName" label="销售属性名字" width="180" />
            <el-table-column label="销售属性值">
              <template #="{ row }">
                <el-input v-if="row.flag" v-model="row.saleAttrValue" size="small" @blur="blurSaleInput(row)" />
                <el-button v-else size="small" type="primary" icon="Plus" @click="addSaleVale(row)"></el-button>

                <el-tag style="margin-left: 5px" v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag.name" class="mx-1" closable type="success" @close="deleteTag(index, row)">
                  {{ tag.saleAttrValueName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #="{ row, $index }">
                <el-button type="danger" icon="Delete" size="small" circle @click="deleteSaleAttr(row, $index)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item>
          <el-button :disabled="saleAttrTable.length == 0" type="primary" @click="save($parent)">保存</el-button>
          <el-button type="danger" @click="cancel($parent)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useCategoryStore } from '@/store/module/category'
import { HasSaleAttr, SpuData, SaleAttr, SpuImg } from '@/utils/api/product/spu/type'
import { computed, onMounted, reactive, ref } from 'vue'
import type { UploadProps } from 'element-plus'
import { reqAllSaleAttr, reqAllTradeMark, reqAddSpu, reqSpuImageList, reqSpuHasSaleAttr, reqUpdateSpu } from '@/utils/api/product/spu'
import { TradeMark } from '@/utils/api/product/trademark/type'

const categoryStore = useCategoryStore()
const labelPosition = ref('right')

// 品牌的数据
const trademark = ref<TradeMark[]>([])
// 未过滤的图片列表
const firstImgList = ref<any[]>([])
// 全部的销售属性
const allSaleAttr = ref<HasSaleAttr[]>([])
// 销售属性表格
const saleAttrTable = ref<SaleAttr[]>([])

// 收集的spu参数
let spuParams = reactive<SpuData>({
  category3Id: '',
  spuName: '',
  tmId: '',
  description: '',
  spuImageList: [],
  spuSaleAttrList: []
})

// spu销售属性
const spuSaleAttr = ref()
// 图片
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// 图片上传之前
const handleBeforeUpload = (file: any) => {
  if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件务必小于3M'
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件务必PNG|JPG|GIF'
    })
    return false
  }
}

onMounted(() => {
  // 新增和修改通用的
  getTrademark()
  getSaleAttr()
})

// 获取品牌数据
const getTrademark = async () => {
  const res = await reqAllTradeMark()
  if (res.data.code == 200) {
    trademark.value = res.data.data
  }
}

// 获取全部的销售属性
const getSaleAttr = async () => {
  const res = await reqAllSaleAttr()
  if (res.data.code == 200) {
    allSaleAttr.value = res.data.data
  }
}

// 添加销售属性
const addSaleAttr = () => {
  const selectSale = allSaleAttr.value.filter((item: HasSaleAttr) => {
    return item.id == spuSaleAttr.value
  })

  saleAttrTable.value.push({
    baseSaleAttrId: spuSaleAttr.value,
    saleAttrName: selectSale[0].name,
    spuSaleAttrValueList: [],
    flag: false
  })
  allSaleAttr.value = allSaleAttr.value.filter((item: HasSaleAttr) => {
    return item.id != spuSaleAttr.value
  })
  spuSaleAttr.value = ''
}

// 添加销售属性值
const addSaleVale = (row: SaleAttr) => {
  row.flag = true
}

// 销售属性值的输入框
const blurSaleInput = (row: SaleAttr) => {
  row.spuSaleAttrValueList.push({
    saleAttrValueName: row.saleAttrValue!,
    baseSaleAttrId: row.baseSaleAttrId
  })
  row.saleAttrValue = ''
  row.flag = false
}

// 删除标签
const deleteTag = (index: number, row: SaleAttr) => {
  row.spuSaleAttrValueList.splice(index, 1)
}

// 删除表格某个销售属性
const deleteSaleAttr = (row: SaleAttr, index: number) => {
  saleAttrTable.value.splice(index, 1)
  allSaleAttr.value.push({
    id: Number(row.baseSaleAttrId),
    name: row.saleAttrName
  })
}

// 保存按钮
const save = async ($parent: any) => {
  spuParams.spuImageList = firstImgList.value.map((item: any) => {
    return { imgName: item.name, imgUrl: (item.response && item.response.data) || item.url }
  })
  spuParams.spuSaleAttrList = saleAttrTable.value

  spuParams.category3Id = categoryStore.c3Id

  // 更新
  if (spuParams.id) {
    const res = await reqUpdateSpu(spuParams)
    if (res.data.code == 200) {
      $parent.$parent.change_is_show_add()
      $parent.$parent.getSpu()
      ElMessage.success('更新成功')
      clearData()
    }
  } else {
    // 保存
    const res = await reqAddSpu(spuParams)
    if (res.data.code == 200) {
      $parent.$parent.change_is_show_add()
      $parent.$parent.getSpu()
      ElMessage.success('新增成功')
      clearData()
    }
  }
}

// 取消按钮
const cancel = ($parent: any) => {
  $parent.$parent.change_is_show_add()
  // 清空数据
  clearData()
}

// 点击修改请求该spu的图片列表
const getImageList = async (spuId: number) => {
  const res = await reqSpuImageList(spuId)
  const newImg = res.data.data.map((item: SpuImg) => {
    return {
      uid: item.uid,
      name: item.imgName,
      url: item.imgUrl,
      status: item.status
    }
  })
  firstImgList.value = newImg as any
}

// 获取SPU的销售属性
const getHasSpuSale = async (spuId: number) => {
  const res = await reqSpuHasSaleAttr(spuId)
  saleAttrTable.value = res.data.data
  allSaleAttr.value = allSaleAttr.value.filter((item: HasSaleAttr) => {
    return res.data.data.every((i2: any) => {
      return i2.saleAttrName !== item.name
    })
  })
}

// 点击父组件修改按钮请求图片和销售属性
const clickEdit = (row: SpuData) => {
  Object.assign(spuParams, row)
  getImageList(row.id!)
  getHasSpuSale(row.id!)
}

// 计算出当前未选的个数
let unselectSaleAttr = computed(() => {
  return allSaleAttr.value.length
})

// 清空数据
const clearData = () => {
  Object.assign(spuParams, {
    category3Id: '',
    spuName: '',
    tmId: '',
    description: '',
    spuImageList: [],
    spuSaleAttrList: []
  })
  firstImgList.value = []
  saleAttrTable.value = []
  getSaleAttr()
  getTrademark()
}

// 暴露
defineExpose({ clickEdit })
</script>

<style scoped></style>
